﻿using AyFrame.IServices;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AyFrame.WebApi.Filters
{
    /// <summary>
    /// 权限Attribute
    /// TODO 怎么可以不用在特性上写死权限串，可通过配置或库来识别对应方法的权限串，再加以验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class PermissionAttribute : Attribute, IAuthorizationFilter
    {
        readonly List<string> _permissions;
        public PermissionAttribute(params string[] permissions)
        {
            _permissions = permissions.ToList();
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User == null || 
                context.HttpContext.User.Identity == null || 
                !context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new ForbidResult();
            }

            var headers = new Dictionary<string, string>();
            foreach (var item in context.HttpContext.Request.Headers)
            {
                if (item.Key == "Authorization" || item.Key == "Api-Key" || item.Key == "passport".ToUpper())
                {
                    headers.Add(item.Key, item.Value);
                }
            }

            using(var container = Startup.Host.Services.CreateScope())
            {
                var _authSer = container.ServiceProvider.GetService<IAuthService>();
                // TODO 获取用户权限
            }
        }
    }
}
